﻿using NativeWifi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WiFiAccessPointScanner
{
    public class WlanAdapter
    {
        public TraceEntry CollectTraceEntry(int traceNumber = 1)
        {
            WlanClient client = new WlanClient();
            WlanClient.WlanInterface wlanIface = client.Interfaces != null && client.Interfaces.Count() > 0 ? client.Interfaces.First() : null;

            if(wlanIface != null)
            {
                TraceEntry trace = new TraceEntry { TraceNumber = traceNumber };
                Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
                var macAddresses = GetSSMACAddresses(wlanIface);

                foreach (Wlan.WlanAvailableNetwork network in networks)
                {
                    string apName = GetStringForSSID(network.dot11Ssid);
                    string mac = macAddresses.ContainsKey(apName) ? macAddresses[apName].Key : string.Empty;
                    uint sq = network.wlanSignalQuality;
                    int ss = macAddresses.ContainsKey(apName) ? macAddresses[apName].Value : 0;

                    trace.SignalStrengthSamples.Add(new APSignalStrengthSample(apName, mac, sq, ss));
                }

                return trace;
            }

            return null;
        }

        private string GetStringForSSID(Wlan.Dot11Ssid ssid)
        {
            return Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
        }

        private Dictionary<string, KeyValuePair<string,int>> GetSSMACAddresses(WlanClient.WlanInterface wlanIface)
        {
            Dictionary<string, KeyValuePair<string, int>> macAddresses = new Dictionary<string, KeyValuePair<string, int>>();
            Wlan.WlanBssEntry[] wlanBssEntries = wlanIface.GetNetworkBssList();

            foreach (Wlan.WlanBssEntry wlanBssEntry in wlanBssEntries)
            {
                byte[] macAddr = wlanBssEntry.dot11Bssid;
                var macAddrLen = (uint)macAddr.Length;
                var str = new string[(int)macAddrLen];

                for (int i = 0; i < macAddrLen; i++)
                    str[i] = macAddr[i].ToString("x2");

                string mac = string.Join(":", str);
                macAddresses[GetStringForSSID(wlanBssEntry.dot11Ssid)] = new KeyValuePair<string,int>(mac, wlanBssEntry.rssi);
            }

            return macAddresses;
        }
    }
}
